#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from typing import List, Dict
from .base import FilterRule
import re

class TrivialWhitespaceFilter(FilterRule):
    """只改空格或换行的过滤规则（首尾空行忽略）"""

    def should_filter(self, add_content: str, remove_content: str, hunk_changes: List[Dict]) -> bool:
        """判断是否为仅格式层面的改动"""
        
        def normalize_lines(content: str) -> List[str]:
            """去掉首尾空行，保留中间空行"""
            lines = content.splitlines()
            while lines and not lines[0].strip():
                lines.pop(0)
            while lines and not lines[-1].strip():
                lines.pop()
            return lines

        add_lines = normalize_lines(add_content)
        remove_lines = normalize_lines(remove_content)

        # 如果行数不同，先不直接返回 False，允许首尾空行差异
        if len(add_lines) != len(remove_lines):
            # 只要去掉空白后内容一致，就视为仅空白改动
            add_text = re.sub(r'\s+', '', add_content)
            remove_text = re.sub(r'\s+', '', remove_content)
            return add_text == remove_text

        # 对每行去掉所有空白字符后比较
        for a, r in zip(add_lines, remove_lines):
            if re.sub(r'\s+', '', a) != re.sub(r'\s+', '', r):
                return False

        return True

    def get_filter_reason(self) -> str:
        return "trivial_whitespace"
